package com.atguigu.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.yygh.oss.service.FileService;
import com.atguigu.yygh.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    //文件上传到阿里云
    @Override
    public String upload(MultipartFile file) {
        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        try {
            //创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);

            //获取上传文件流
            InputStream inputStream = file.getInputStream();

            // 第一个参数Bucket名称
            // 第二个参数 上传文件路径+名称    01.jpg      /2021/11/12/01.jpg
            // 第三个参数 文件输入流
            String filename = file.getOriginalFilename();
            //在文件名称中添加唯一值 uuid
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            filename = uuid + filename;

            //根据当前日期进行分组
            //2024/04/13
            String dateUrl = new DateTime().toString("yyyy/MM/dd");
            //2024/04/13/nkankl45vsa.jpg
            filename = dateUrl+"/"+filename;

            ossClient.putObject(bucketName,filename,inputStream);
            //关闭OSSClient
            ossClient.shutdown();

            //返回上传文件在阿里云路径
            String url = "https://" + bucketName + "." + endpoint + "/" + filename;
            return url;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
